#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yuri'

import time

import pytest
from py._xmlgen import html
from webrunner.common.tools import get_driver, get_env

driver = get_driver()


def getUser(uType: str) -> tuple:
    """
    :param uType: safe5
    :return: user, passwd
    """
    safeUser = uType.upper() + '_U'
    safePasswd = uType.upper() + '_P'
    return get_env(safeUser), get_env(safePasswd)


@pytest.fixture
def login():
    def hello(uType):
        print(uType)
    return hello


def pytest_configure(config):
    """
    Modify Environment info of HTML report
    """
    config._metadata['Project Name'] = 'demo UI auto test'
    try:
        config._metadata.pop('JAVA_HOME')
    except Exception:
        pass


@pytest.mark.optionalhook
def pytest_html_results_summary(prefix):
    """
    Modify Summary info of HTML report
    """
    prefix.extend([html.p('Department: {}'.format('demo QA team'))])
    import socket
    prefix.extend([html.p('Hostname: {}'.format(socket.gethostname()))])


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    1. Solve Chinese encode
    2. Add screenshots when the test fails
    3. Add descriptions (use comments of test_functions) in html report
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    report.nodeid = report.nodeid.encode(
        'utf-8').decode("utf-8")  # if Chinese in case
    # if report.when == 'call' or report.when == 'setup':
    if report.when == 'call':
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            report.longrepr = report.longrepr.reprcrash.message
            time.sleep(1)
            screen_img = driver.get_screenshot_as_base64()
            html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ' \
                'onclick="window.open(this.src)" align="right"/></div>' % screen_img
            extra.append(pytest_html.extras.html(html))
        report.extra = extra
        report.description = str(item.function.__doc__)
        case = item.funcargs.get('case', None)
        report.case = case


@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    """
    Delete link cell header in HTML report
    """
    cells.pop(-1)
    cells.insert(1, html.th('Description'))
    cells.insert(-2, html.th('keyPoints'))


@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    """
    Delete link cell row in HTML report
    """
    cells.pop(-1)
    cells.insert(1, html.td(report.description))
    if report.case:
        cells.insert(-2, html.td(report.case.get('keyPoints')))
    else:
        cells.insert(-2, html.td("no DDT"))


@pytest.fixture(scope="function")
def func_hook():

    yield driver


@pytest.fixture(scope="class")
def class_hook():

    yield driver


@pytest.fixture(scope="module")
def module_hook():

    yield driver


@pytest.fixture(scope="session")
def session_hook():

    yield driver


@pytest.fixture(scope="package")
def package_hook():
    yield driver


def pytest_sessionfinish():
    driver.quit()
